﻿#include "DDBController.h"

#include <QApplication>
#include <QDebug>

#include "DHeader.h"
#include "DSqliteMgr.h"

DDBController::DDBController() {}

void DDBController::loadSubmitList()
{
    DObjectPtr<DSqliteMgr> sqliteMgr;

    // list
    std::map<IDStudent, std::map<QDate, std::vector<DOneHomeworkSubmit>>>
        mapSubmit;
    const std::vector<QSqlRecord> vecSubmitRecord =
        sqliteMgr->execSQL("SELECT * FROM homework_list");

    for (const auto& r : vecSubmitRecord)
    {
        DOneHomeworkSubmit submit;
        submit.nID = r.value("id").toInt();
        submit.nStuentID = r.value("student_id").toString().toInt();
        submit.nHomeworkTypeID = r.value("homeworkType_id").toInt();
        QString s = r.value("submit_date").toString();
        submit.dtSubmit = QDate::fromString(s, "yyyy-MM-dd");
        mapSubmit[submit.nStuentID][submit.dtSubmit].push_back(submit);
    }
    sqliteMgr->setSubmitData(mapSubmit);
}

void DDBController::loadDB()
{
    loadSubmitList();

    DObjectPtr<DSqliteMgr> sqliteMgr;

    // student
    std::vector<DStudent> vecStudent;
    const std::vector<QSqlRecord> vecStudentRecord =
        sqliteMgr->execSQL("SELECT * FROM student");

    for (const auto& r : vecStudentRecord)
    {
        DStudent student;
        student.nID = r.value("id").toInt();
        student.strNumber = r.value("number").toString().toStdString();
        student.strName = r.value("name").toString().toStdString();
        student.strMemo = r.value("memo").toString().toStdString();
        vecStudent.push_back(student);
    }

    sqliteMgr->setStudentData(vecStudent);

    // subject
    const std::vector<QSqlRecord> vecHomeworkTypeRecord =
        sqliteMgr->execSQL("SELECT * FROM homework_type");

    std::vector<DSubject> vecSubject;
    const std::vector<QSqlRecord> vecSubjectRecord =
        sqliteMgr->execSQL("SELECT * FROM subject");

    for (const auto& r : vecSubjectRecord)
    {
        DSubject subject;
        subject.nID = r.value("id").toInt();
        subject.strName = r.value("name").toString().toStdString();

        for (const auto& r : vecHomeworkTypeRecord)
        {
            const int nSubjectID = r.value("subject_id").toInt();
            if (nSubjectID == subject.nID)
            {
                DHomeworkType homeworkType;
                homeworkType.nID = r.value("id").toInt();
                homeworkType.strName = r.value("name").toString().toStdString();
                subject.vecHomeworkType.push_back(homeworkType);
            }
        }

        vecSubject.push_back(subject);
    }

    sqliteMgr->setSubjectData(vecSubject);
}
